<template>
  <div class="product-edit-image">
    <el-upload
      action="#"
      :multiple="true"
      :file-list="fileList"
      :limit="4"
      list-type="picture-card"
      :http-request="uploadImage"
      :on-remove="onRemove"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadProductImage } from "../../../../api/product";

let timer = null;
export default {
  name: "ProductEditImage",
  props: {
    id: {
      type: Number,
      require: true,
    },
    images: {
      type: Array,
    },
  },
  computed: {
    fileList() {
      return this.images.map((image) => ({ url: image.image, id: image.id }));
    },
  },
  methods: {
    async uploadImage({ file }) {
      // console.log('file',file)
      const fd = new FormData();
      fd.append("product", this.id);
      fd.append("image", file);
      const result = await uploadProductImage(fd);
      this.$emit("update:image", [...this.images, result]);
      console.log("图片上传完成！");
      // 防抖
      clearTimeout(timer);
      timer = setTimeout(() => {
        console.log("多张图片上传完成！");
        this.$emit("update");
      }, 300);
    },
    async onRemove(data) {
      await this.$api.deleteProductImage(data);
      const index = this.images.findIndex((image) => image.id === data.id);
      const arr = [...this.images].splice(index, 1);
      this.$emit("update:images", arr);
    },
  },
};
</script>

<style scoped></style>
